/*
 * Copyright (c) 2018. czmc All Rights Reserved.
 * Author: czmc
 * Email: zxc6355533@163.com
 * Encoding: UTF-8
 */

package top.stime21.myneighbours.api

import com.google.gson.GsonBuilder
import okhttp3.Cache
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import top.stime21.myneighbours.App
import java.io.File
import java.util.concurrent.TimeUnit


class ApiManager private constructor() {
    private val okHttpClient: OkHttpClient
    var retrofit: Retrofit
    var dataApi: DataApi


    init {
        init()
        val paramInterceptor = ParamInterceptor()
        val mHeadIntercetor = HeadIntercetor()
        val cacheFile = File(App.Companion.ins!!.cacheDir, "cache")
        val cache = Cache(cacheFile, (1024 * 1024 * 100).toLong()) //100Mb
        // SSLContext sslContext = SslUtils.getSslContextForCertificateFile(App.ins(), "stime21.top.cer");
        okHttpClient = OkHttpClient.Builder()
                .readTimeout(7676, TimeUnit.MILLISECONDS)
                .addNetworkInterceptor(paramInterceptor)
                .addInterceptor(mHeadIntercetor)
                //  .sslSocketFactory(sslContext.getSocketFactory())
                .cache(cache)
                .build()


        val gson = GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").serializeNulls().create()
        retrofit = Retrofit.Builder()
                .client(okHttpClient)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonDecoderConverterFactory.create(gson))
                .baseUrl(API_URL)
                .build()

        dataApi = retrofit.create(DataApi::class.java)
    }

    //在访问HttpMethods时创建单例
    private object SingletonHolder {
         val INSTANCE = ApiManager()
    }

    external fun init()

    companion object {
        var SECRET = ""
        var API_URL = ""
        //获取单例
        fun ins(): ApiManager {
            return SingletonHolder.INSTANCE
        }

        init {
            System.loadLibrary("secret-lib")
        }
    }
}